package rad.framework.jsf;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import rad.framework.richfaces.EntityTreeNode;
import rad.framework.richfaces.FolderTreeNode;

/**
 * Used with Rich Faces Ordering List.
 * 
 * @author boudyacho
 */
public class EntityTreeNodeConverter implements Converter {

	public Object getAsObject(FacesContext context, UIComponent comp,
			String value) throws ConverterException {
		if (value == null || value.trim().length() == 0) {
			return null;
		}
		UIData data = (UIData) comp;
		return get((List) data.getValue(), value);
	}

	protected EntityTreeNode get(List list, Object key) {
		if (list.isEmpty()) {
			return null;
		}
		EntityTreeNode node = (EntityTreeNode) list.get(0);
		if (node.getKey() instanceof Long) {
			key = Long.valueOf((String) key);
		}
		FolderTreeNode folder = (FolderTreeNode) node.getParent();
		return (EntityTreeNode) folder.getChild(key);
	}

	public String getAsString(FacesContext ctx, UIComponent comp, Object object)
			throws ConverterException {
		if (object == null) {
			return null;
		}
		return ((EntityTreeNode) object).getKey().toString();
	}
}
